<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;

/**
 * 周期购订单
 */
class Weekorder extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['notify','paysuccess'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //确认订单页面
    public function makeorder(){
        $user = $this->auth->getUser();
        $weekgoods_id = input('weekgoods_id','');//周期购商品
        $weekgoods = db('weekgoods')->where(['id'=>$weekgoods_id])->find();
        $address_id = input('address_id','');//地址
        if($address_id){
            $address = db('address')->where(['id'=>$address_id])->find();
            $data['address'] = $address;
        }else{
            $data['address'] = [];
        }
        $data['weekgoods'] = $weekgoods;
        //优惠券
        $usercoupon = db('usercoupon')->where(['user_id'=>$user->id,'topmoney'=>['<=',$weekgoods['price']]])->select();
        $data['usercoupon'] = $usercoupon;
        //发货时间
        $week = input('week',1);
        $nowweek = date('w')==0?7:date('w');
        $Monday = strtotime('today -'.($nowweek-$week).'day');
        $num = $weekgoods['num'];
        
        if($Monday<time()){
            $Monday += 7*24*60*60;
        }
        if($Monday<time()+2*24*60*60){
            $Monday += 7*24*60*60;
        }
        // dump($Monday);
        // dump(date('Y-m-d',$Monday));
        // dump(time()+2*24*60*60);die;
        $weeklist = [];
        for($i=0;$i<$num;$i++){
            $weeklist[] = date('Y-m-d',$Monday+$i*7*24*60*60);
        }
        $data['weeklist'] = $weeklist;
        $this->success('ok',$data);
    }
    //创建订单
    public function createorder(){
        $user = $this->auth->getUser();
        $weekgoods_id = input('weekgoods_id','');//周期购商品
        $weekgoods = db('weekgoods')->where(['id'=>$weekgoods_id])->find();
        $address_id = input('address_id','');//地址
        if(!$address_id){
            $this->error('请选择收货地址');
        }
        $address = db('address')->where(['id'=>$address_id])->find();
        $week = input('week',1);
        $usercoupon_id = input('usercoupon_id','');//用户优惠券id
        //创建主订单
        $usercoupon = db('usercoupon')->where(['id'=>$usercoupon_id])->find();
        if($usercoupon){
            $total = $weekgoods['price']-$usercoupon['money'];
        }else{
            $total = $weekgoods['price'];
        }
        $note = input('note','');
        $data = [
            'order_sn'=>'week'.date('YmdHis').rand(1000,9999),
            'user_id'=>$user->id,
            'clientname'=>$address['name'],
            'clientmobile'=>$address['mobile'],
            'clientaddress'=>$address['city'].' '.$address['address'],
            'weekgoods_id'=>$weekgoods_id,
            'num'=>$weekgoods['num'],
            'total'=>$total,
            'usercoupon_id'=>$usercoupon_id,
            'money'=>$weekgoods['price'],
            'score'=>$weekgoods['score'],
            'status'=>1,
            'createtime'=>time(),
            'week'=>$week,
            'note'=>$note,
        ];
        $res = db('weekorder')->insertGetId($data);
        //创建主订单
        $arr =[
            'user_id'=>$user->id,
            'order_sn'=>$data['order_sn'],
            'type'=>1,
            'status'=>1,
            'createtime'=>time()
        ];
        db('userorder')->insert($arr);
        if($res){
            $this->success('ok',['order_id'=>$res]);
        }else{
            $this->error('创建订单失败');
        }
    }
    //余额支付
    public function moneypayorder(){
        $user = $this->auth->getUser();
        $order_id = input('order_id','');
        if(!$order_id){
            $this->error('缺失参数order_id');
        }
        $order = db('weekorder')->where(['id'=>$order_id])->find();
        $isscore = input('isscore',0);//是否适用积分
        $score = 0;
        $total = $order['total'];
        $usescore = 0;
        if($isscore){
            $scorefee = Config::get('site.scorefee');
            $score = $user->score/$scorefee;
            if($score){
                $total = $order['total']-$score;
                $usescore = $user->score;
            }
        }
        
        if($total>$user->money){
            $this->error('余额不足');
        }
        db('user')->where(['id'=>$user->id])->setDec('money',$total);
        if($score){
            db('user')->where(['id'=>$user->id])->update(['score'=>0]);
            addscorelog($user->id,$user->score,1,'购买周期购商品');
        }
        //加记录
        addmoneylog($user->id,$total,1,'购买周期购商品');
        db('weekorder')->where(['id'=>$order_id])->update(['status'=>2,'paytype'=>2,'paytime'=>time(),'usescore'=>$usescore]);
        db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>2]);
        $this->paysuccess($order_id);
        $this->success('支付成功');
    }
    //支付成功
    public function paysuccess($order_id){
        $order = db('weekorder')->where(['id'=>$order_id])->find();
        $weekgoodsitem = db('weekgoodsitem')->where(['weekgoods_id'=>$order['weekgoods_id'],'isdefault'=>1])->select();
        $arr = [];
        foreach($weekgoodsitem as $k=>$v){
            $str = [];
            $str['id'] = $v['id'];
            $str['name'] = $v['name'];
            $str['num'] = $v['defaultnum'];
            $arr[] = $str;
        }
        $week = $order['week'];
        $nowweek = date('w')==0?7:date('w');
        $Monday = strtotime('today -'.($nowweek-$week).'day');
        $num = $order['num'];
        if($Monday<time()){
            $Monday += 7*24*60*60;
        }
        $weeklist = [];
        for($i=0;$i<$num;$i++){
            $weeklist[] = date('Y-m-d',$Monday+$i*7*24*60*60);
        }
        foreach($weeklist as $k=>$v){
            $data['weekorder_id'] = $order_id;
            $data['order_sn'] = 'Z'.date('YmdHis').rand(1000,9999);
            $data['goodsjson'] = json_encode($arr,320);
            $data['status'] = 1;
            $data['createtime'] = strtotime($v);
            db('weekorderitem')->insert($data);
        }
        
    }
    //获取支付参数
    public function getorderpaymsg(){
        $user = $this->auth->getUser();
        $order_id = input('order_id');
        $order = db('weekorder')
            ->where('id',$order_id)
            ->find();
        if ($order['status'] != 1){
            $this->error('订单状态错误');
        }
        $isscore = input('isscore',0);//是否适用积分
        $score = 0;
        $total = $order['total'];
        $usescore = 0;
        if($isscore){
            $scorefee = Config::get('site.scorefee');
            $score = $user->score/$scorefee;
            if($score){
                $total = $order['total']-$score;
                $usescore = $user->score;
                db('weekorder')->where(['id'=>$order_id])->update(['usescore'=>$usescore]);
            }
        }
        $openid = $user->openid;
        $out_trade_no = 'week'.date('YmdHis').rand(1000,9999);
        //更新订单的支付单号
        db('weekorder')
            ->where('id',$order_id)
            ->update([
                'order_sn'=>$out_trade_no
            ]);
        $params = [
            'type'         => 'wechat',
            'orderid'      => $out_trade_no,
            'title'        => '购买周期购商品',
            'amount'       => $total,
            'method'       => 'miniapp',
            'openid'       => $openid,
            'notifyurl'    => $this->request->domain().'/api/weekorder/notify/paytype/wechat',
        ];
        // $params['amount'] = 0.01;
        $res =  Service::submitOrder($params);
        $this->success('支付串',$res);
    }
    //支付回调
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
            $order = db('weekorder')
                ->where('order_sn',$out_trade_no)
                ->find();
            if ($order && $order['status'] == 1){
                //更新订单状态
                db('weekorder')
                ->where('id',$order['id'])
                ->update([
                    'status'=>2,
                    'paytime'=>time()
                ]);
                if($order['usescore']){
                    db('user')->where(['id'=>$order['user_id']])->update(['score'=>0]);
                    addscorelog($order['user_id'],$order['usescore'],1,'购买周期购商品');
                }
                db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>2]);
                $this->paysuccess($order['id']);
            }


        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
    //订单详情
    public function getorderinfo(){
        $order_id = input('order_id','');
        if(!$order_id){
            $this->error('缺失参数');
        }
        $weekorder = db('weekorder')->where(['id'=>$order_id])->find();//周期购订单
        if($weekorder['usercoupon_id']){
            $usercoupon = db('usercoupon')->where(['id'=>$weekorder['usercoupon_id']])->find();
            $weekorder['couponmoney'] = $usercoupon['money'];
        }else{
            $weekorder['couponmoney'] = 0;
        }
        $weekorder['createtime'] = date('Y-m-d H:i',$weekorder['createtime']);
        if($weekorder['paytime']){
            $weekorder['paytime'] = date('Y-m-d H:i',$weekorder['paytime']);
        }else{
            $weekorder['paytime'] = '';
        }
        
        //子订单
        $weekorderitem = db('weekorderitem')->where(['weekorder_id'=>$order_id])->order('createtime asc')->select();
        foreach($weekorderitem as $k=>$v){
            $weekorderitem[$k]['createtime'] = date('Y-m-d',$v['createtime']);
            $weekorderitem[$k]['fatime'] = date('Y-m-d H:i',$v['fatime']);
            $weekorderitem[$k]['wantime'] = date('Y-m-d H:i',$v['wantime']);
            $week = date('w',$v['createtime']);
            if($week==0){
                $weekorderitem[$k]['weekstr'] = '周日';
            }
            if($week==1){
                $weekorderitem[$k]['weekstr'] = '周一';
            }
            if($week==2){
                $weekorderitem[$k]['weekstr'] = '周二';
            }
            if($week==3){
                $weekorderitem[$k]['weekstr'] = '周三';
            }
            if($week==4){
                $weekorderitem[$k]['weekstr'] = '周四';
            }
            if($week==5){
                $weekorderitem[$k]['weekstr'] = '周五';
            }
            if($week==6){
                $weekorderitem[$k]['weekstr'] = '周六';
            }
            $weekorderitem[$k]['goodsjson'] = json_decode($v['goodsjson'],true);

        }
        $weekgoods = db('weekgoods')->where(['id'=>$weekorder['weekgoods_id']])->find();
        $data['weekgoods'] = $weekgoods;
        $data['weekorder'] = $weekorder;
        $data['weekorderitem'] = $weekorderitem;
        $this->success('ok',$data);
    }
    //确认收货
    public function confirmorder(){
        $order_id = input('order_id','');
        if(!$order_id){
            $this->error('缺失参数');
        }
        $weekorderitem = db('weekorderitem')->where(['id'=>$order_id])->find();
        db('weekorderitem')->where(['id'=>$order_id])->update(['status'=>3,'wantime'=>time()]);
        $check = db('weekorderitem')->where(['weekorder_id'=>$weekorderitem['weekorder_id'],'status'=>1])->count();
        if(!$check){
            $order = db('weekorder')->where(['id'=>$weekorderitem['weekorder_id']])->find();
            db('weekorder')->where(['id'=>$weekorderitem['weekorder_id']])->update(['status'=>4,'wantime'=>time()]);

            db('userorder')->where(['order_sn'=>$order['order_sn']])->update(['status'=>4]);
        }
        $this->success('确认收货成功');
    }
    //修改菜品页面
    public function editgoodslist(){
        $weekgoods_id = input('weekgoods_id','');
        $weekgoods = db('weekgoods')->where(['id'=>$weekgoods_id])->find();
        $weekgoodsitem = db('weekgoodsitem')->where(['weekgoods_id'=>$weekgoods_id])->select();//商品列表
        // dump($weekgoodsitem);die;
        $catenamearr = [];
        $list = [];
        foreach($weekgoodsitem as $k=>$v){
            if(!in_array($v['catename'],$catenamearr)){
                $catenamearr[] = $v['catename'];
            }
        }
        foreach($catenamearr as $k=>$v){
            $arr['name'] = $v;
            $arr['list'] = db('weekgoodsitem')->where(['weekgoods_id'=>$weekgoods_id,'catename'=>$v])->select();
            $list[] = $arr;
        }
        // dump($list);die;
        //默认商品
        $weekgoodsitem = db('weekgoodsitem')->where(['weekgoods_id'=>$weekgoods_id,'isdefault'=>1])->select();
        $arr = [];
        foreach($weekgoodsitem as $k=>$v){
            $str = [];
            $str['id'] = $v['id'];
            $str['name'] = $v['name'];
            $str['num'] = $v['defaultnum'];
            $arr[] = $str;
        }
        $data['weekgoods'] = $weekgoods;
        $data['list'] = $list;
        $data['delist'] = $arr;
        $this->success('ok',$data);
    }
    //修改菜品方法
    public function editgoods(){
        $weekorderitem_id = input('weekorderitem_id','');
        if(!$weekorderitem_id){
            $this->error('缺失参数');
        }
        $weekorderitem = db('weekorderitem')->where(['id'=>$weekorderitem_id])->find();
        $day = 2;//提前的2天
        if($weekorderitem['createtime']<=time()+$day*24*60*60){
            $this->error('该订单距离发货时间较近不可更换');
        }
        // $type = input('type',1);//1默认菜品 2自选菜品
        $goodsjson = input('goodsjson','');
        $goodsjson = htmlspecialchars_decode($goodsjson);
        $res = db('weekorderitem')->where(['id'=>$weekorderitem_id])->update(['goodsjson'=>$goodsjson]);
        if($res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }

    }
}
